package com.ruoyi.system.util;

/**
 * @author : gaosheng
 * @Date :2025/9/12 17:42
 */
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class TiffThumbnailUtil {

    public static void generateThumbnail(File inputTiff, File outputImg,
                                         int maxWidth, int maxHeight) throws IOException {
        if (maxWidth <= 0 && maxHeight <= 0) {
            maxWidth = 512; // 给个安全默认值
            maxHeight = 512;
        }
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("TIFF");
        if (!readers.hasNext()) {
            throw new IOException("没有找到TIFF ImageReader，请确认已引入 TwelveMonkeys: imageio-tiff");
        }
        ImageReader reader = readers.next();

        try (ImageInputStream iis = ImageIO.createImageInputStream(inputTiff)) {
            reader.setInput(iis, true, true);

            int srcW = reader.getWidth(0);
            int srcH = reader.getHeight(0);

            // 计算目标尺寸（等比缩放，且不放大）
            Dimension target = fitSize(srcW, srcH, maxWidth, maxHeight);
            int dstW = Math.max(1, target.width);
            int dstH = Math.max(1, target.height);

            // 子采样步长（确保读出的宽高 >= 目标，避免后续再放大过多）
            int subX = Math.max(1, (int) Math.floor((double) srcW / dstW));
            int subY = Math.max(1, (int) Math.floor((double) srcH / dstH));
            int sub = Math.max(1, Math.min(subX, subY));

            ImageReadParam param = reader.getDefaultReadParam();
            param.setSourceSubsampling(sub, sub, 0, 0);

            BufferedImage sampled = reader.read(0, param);
            if (sampled == null) {
                throw new IOException("读取TIFF失败，返回null图像");
            }

            // 统一转换为安全的 sRGB 类型，避免 TYPE_CUSTOM/索引色 导致变换失败
            BufferedImage safe = toSRGB(sampled);

            // 用 Graphics2D 缩放（比 AffineTransformOp 更“宽容”）
            BufferedImage thumb = new BufferedImage(dstW, dstH,
                    safe.getColorModel().hasAlpha() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
            Graphics2D g = thumb.createGraphics();
            // 插值 & 抗锯齿
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.drawImage(safe, 0, 0, dstW, dstH, null);
            g.dispose();
//        给刘子康  阳光让给的
            // 写出（jpg 无透明，自动铺白底）
            write(thumb, outputImg);
        } finally {
            reader.dispose();
        }
    }

    private static Dimension fitSize(int w, int h, int maxW, int maxH) {
        double sx = (maxW > 0) ? (double) maxW / w : 1.0;
        double sy = (maxH > 0) ? (double) maxH / h : 1.0;
        double s = Math.min(Math.min(sx, sy), 1.0); // 不放大
        int nw = (int) Math.max(1, Math.round(w * s));
        int nh = (int) Math.max(1, Math.round(h * s));
        return new Dimension(nw, nh);
    }

    /** 把任意 BufferedImage 转为 sRGB 的 RGB/ARGB */
    private static BufferedImage toSRGB(BufferedImage src) {
        int type = src.getColorModel().hasAlpha() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
        if (src.getType() == type) return src;

        BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), type);
        Graphics2D g = dst.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(src, 0, 0, null);
        g.dispose();
        return dst;
    }

    private static void write(BufferedImage img, File out) throws IOException {
        String name = out.getName().toLowerCase();
        boolean png = name.endsWith(".png");
        if (!png && img.getColorModel().hasAlpha()) {
            // jpg 不支持透明 → 铺白底
            BufferedImage rgb = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = rgb.createGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, rgb.getWidth(), rgb.getHeight());
            g.drawImage(img, 0, 0, null);
            g.dispose();
            ImageIO.write(rgb, "jpg", out);
        } else {
            ImageIO.write(img, png ? "png" : "jpg", out);
        }
    }

    public static void main(String[] args) throws Exception {
        File input = new File("G:\\朝鲜影像.tif");
        File output = new File("G:\\demo_thumb.jpg");
        generateThumbnail(input, output, 512, 512);
        System.out.println("缩略图生成完成: " + output.getAbsolutePath());
    }
}